<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use tree\Tree;

class Index extends Controller
{
    public function test3()
    {
        $m = Db::name('region')->where('parent_id=0')->select(); //获取一级菜单
        print_r($m);
    }

    /**
     * 获取省份 - 普通形式
     * @return mixed
     */
    public function city()
    {

        $province = Db::name('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $this->assign('province', $province);
        return $this->fetch();
    }

    /*
     * 获取地区
     */
    public function getRegion()
    {
        $parent_id = input('parent_id');
        $data = Db::name('region')->where("parent_id", $parent_id)->select();
        $html = '';
        if ($data) {
            foreach ($data as $h) {
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }
        echo $html;
    }

    /**
     * 获取省份 - layui制作的三级联动
     */
    public function city_layui()
    {
        //  获取省份
        $province = Db::name('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $this->assign('province', $province);
        return $this->fetch();
    }

    /**
     * 获取省份 - bootstrap 制作的三级联动
     */
    public function city_bootstrap()
    {
        //  获取省份
        $province = Db::name('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $this->assign('province', $province);
        return $this->fetch();
    }

    /**
     * layui制作的三级联动-json格式
     */
    public function city_layui_json()
    {
        return $this->fetch();
    }

    /**
     * json格式为
     *
     */
    public function city_list()
    {

//        $data = ['id'=>1,'name'=>'山西省'];
//        $data['city'] = ['id'=>2,'name'=>'太原市'];
//        $data['city']['area'] = [  ['id'=>3,'name'=>'小店区'],['id'=>4,'name'=>'迎泽区']];
//        print_r($data);exit;




        $data = Db::name('region')->select();


        $result  = make_tree($data,0,'id|parent_id|city');
        print_r($result);


    }

    public function render()
    {
        return $this->fetch();
    }

    //将sql转化为json
    public function city_sql2json(){
        $m = Db::name('region');
        $list = $m->where('parent_id=0')->select(); //获取一级菜单;
        foreach($list as $key => $val){
            $list[$key]['city']=$m->where('parent_id='.$val['id'])->select();
            foreach($list[$key]['city'] as $k => $v){
                $list[$key]['city'][$k]['area'] = $m->where('parent_id='.$v['id'])->select();
            }
        }
        $data = json($list);
        print_r($data);exit;

    }




}
